<script setup>
import Info from '../../pojo/Info.js'
import {ref, computed, onBeforeMount} from 'vue'
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import {addInfoApi, deleteInfoApi, getAllInfoApi, updateInfoApi} from "../../apis/infoApi.js";

// 模拟数据（增加同标题数据）
const generateData = async () => [
  new Info(1, '基本情况', '唐超，安徽合肥人，厦门大学理学博士，合肥学院人工智能与大数据学院副教授，合肥学院硕士研究生导师，美国布卢姆菲尔德学院和英国伯明翰大学访问学者，中国计算机学会会员，中国人工智能学会会员，中国计算机学会第十二次会员代表大会会员代表。主要从事人工智能、机器学习、计算机视觉、数字图像处理等方向的研究工作。是IEEE Transactions on Circuits and Systems for Video Technology、Engineering Applications of Artificial Intelligence、Neurocomputing、计算机学报、模式识别与人工智能等期刊审稿人。共发表论文56篇，其中SCI，EI收录论文42篇，主持了各类纵向项目7项，横向项目11项，参与了4项国家自然科学基金项目。', 1),
  new Info(2, '公司简介', '成立时间地点', 2),
  new Info(3, '发展历程', '2010年成立', 1),
  new Info(4, '发展历程', '2020年上市', 2),
  new Info(5, '企业文化', '核心价值观', 1),

]

onBeforeMount(async () => {
  const resp = await getAllInfoApi()
  console.log(resp)
  if (resp.data.code !== 200) {
    ElMessage.error('获取数据失败')
    return
  } else {
    tableData.value = resp.data.data.map(item => new Info(
        item.id,
        item.title,
        item.description,
        item.displayOrder
    ))
  }
  console.log(tableData.value)
})


// 响应式数据
const tableData = ref([])
const searchText = ref('')
const dialogVisible = ref(false)
const formData = ref(new Info())
const isEdit = ref(false)

let treeData = computed(() => {
  const groups = {}
  tableData.value.forEach(item => {
    if (!groups[item.title]) {
      groups[item.title] = {
        id: `group-${item.title}`,
        title: item.title,
        children: [],
        isFolder: true
      }
    }
    groups[item.title].children.push({
      ...item,
      parentTitle: item.title
    })
  })
  return Object.values(groups)
})

let filteredTreeData = computed(() => {
  return treeData.value.filter(group =>
      group.children.some(child =>
          child.title.includes(searchText.value) ||
          child.description.includes(searchText.value)
      )
  ).map(group => ({
    ...group,
    children: group.children.filter(child =>
        child.title.includes(searchText.value) ||
        child.description.includes(searchText.value)
    )
  }))
})

console.log(filteredTreeData.value)
console.log(treeData.value)

const rules = {
  title: [{required: true, message: '请输入标题', trigger: 'blur'}],
  description: [{required: true, message: '请输入描述', trigger: 'blur'}],
  displayOrder: [
    {required: true, message: '请输入排序号', trigger: 'blur'},
    {type: 'number', message: '排序号必须为数字', trigger: 'blur'}
  ]
}

const openDialog = () => {
  formData.value = new Info()
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = (row) => {
  formData.value = {...row}
  isEdit.value = true
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该记录？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    console.log(index)
    console.log(tableData.value[index].id)
    const resp = await deleteInfoApi(tableData.value[index].id)
    console.log(resp)
    if (resp.data.code !== 200) {
      ElMessage.error('删除失败')
      return
    } else {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}


const confirmForm = async (row) => {

  if (isEdit.value) {
    const index = tableData.value.findIndex(item => item.id === row.id)
    const resp = await updateInfoApi(formData.value)
    console.log(resp)
    if (resp.data.code !== 200) {
      ElMessage.error('修改失败')
      return
    } else {
      tableData.value[index] = formData.value
      ElMessage.success('修改成功')
    }
  } else {
    console.log(formData.value)
    const resp = await addInfoApi(formData.value)
    console.log(resp)
    if (resp.data.code !== 200) {
      ElMessage.error('新增失败')
      return
    } else {
      tableData.value.push(formData.value)
      ElMessage.success('新增成功')
    }
  }
  dialogVisible.value = false
}

</script>

<template>
  <div class="container">
    <!-- 搜索和新增区域保持不变 -->
    <div class="operation-header">
      <el-input
          v-model="searchText"
          placeholder="请输入关键词搜索"
          style="width: 300px"
          clearable
      >
        <template #prefix>
          <el-icon>
            <search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog">
        <el-icon>
          <plus/>
        </el-icon>
        新增信息
      </el-button>
    </div>

    <!-- 树形表格 -->
    <el-table
        :data="filteredTreeData"
        row-key="id"
        :tree-props="{ children: 'children' }"
        border
        style="width: 100%"
        height="calc(100vh - 180px)"
    >
      <el-table-column prop="title" label="标题" width="200">
        <template #default="{ row }">
          <span v-if="row.isFolder" class="folder-node">{{ row.title }}</span>
          <span v-else>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="描述">
        <template #default="{ row }">
          <span v-if="!row.isFolder">{{ row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="displayOrder" label="排序号" width="120" align="center">
        <template #default="{ row }">
          <span v-if="!row.isFolder">{{ row.displayOrder }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" align="center">
        <template #default="{ row }">
          <template v-if="!row.isFolder">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon>
                <edit/>
              </el-icon>
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon>
                <delete/>
              </el-icon>
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框保持不变 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑信息' : '新增信息'"
        width="600px"
    >
      <el-form :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入详细描述"
          />
        </el-form-item>
        <el-form-item label="排序号" prop="displayOrder">
          <el-input-number
              v-model="formData.displayOrder"
              :min="1"
              controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 新增树形节点样式 */
.folder-node {
  font-weight: 600;
  color: var(--el-color-primary);
}

/* 调整行高 */
:deep(.el-table .el-table__row) {
  height: 50px;
}

/* 保持原有其他样式 */
.container {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.operation-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 15px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>